import ReactDOM from 'react-dom'
import { useState, memo, useCallback, useMemo } from 'react'

/**
 * 使用userMemo添加依赖项之后，
 * 子组件可以根据父组件的依赖项的改变
 * 来进行自己组件的更新与否
 */

type ChildProps = {
  click: () => void
}
const Child = memo(({ click }: ChildProps) => {
  console.log('child组件更新')
  return (
    <div style={{ backgroundColor: 'skyblue', padding: 5 }}>
      子组件：<button onClick={click}>点击</button>
    </div>
  )
})
type Child2Props = {
  user: { age: number }
}
const Child2 = memo(({ user }: Child2Props) => {
  console.log('Child2 组件更新')
  return (
    <div style={{ backgroundColor: '#abc', padding: 5 }}>
      子组件2 - 年龄： {user.age}
    </div>
  )
})

const App = () => {
  const [count, setCount] = useState(0)
  const [theme, setTheme] = useState('pink')
  const handleClick = useCallback(() => {
    console.log('你点击了子组件的按钮')
    setCount(count + 10)
  }, [count])
  // 这里的回调函数，也只会在依赖项改变的时候
  // 才会执行，所以如果依赖项不变，或者没有依赖项，回调函数基本相当于白写
  const users = useMemo(() => {
    return {
      age: count + 15
      // age: 19
    }
  }, [count])
  return (
    <div style={{ backgroundColor: theme, padding: 10 }}>
      <button onClick={() => setTheme(theme === 'pink' ? 'white' : 'pink')}>
        切换主题
      </button>

      <h1>计数器：{count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>

      <hr />

      {/* 子组件 */}
      <Child click={handleClick} />
      <br />
      <Child2 user={users} />
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))
